﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using AmiEmuLib.AmigaConfiguration;
using System.Diagnostics;
using System.IO;
using System.Collections;
using System.Xml;
using TomanuExtensions;

namespace AmiEmuLib.Configuration.AmigaMemoryMap
{
    /// <summary>
    /// List of amiga models memory maps.
    /// </summary>
    [DebuggerDisplay("Count = {Count}")]
    public static class MemoryMaps
    {
        /// <summary>
        /// List of maps.
        /// </summary>
        private static List<MemoryMap> m_maps = new List<MemoryMap>();

        /// <summary>
        /// Static constructor.
        /// </summary>
        static MemoryMaps()
        {
            using (var stream = StreamExtensions.FromResource(typeof(MemoryMaps), 
                "MemoryMaps.xml"))
            {
                XmlReaderExtensions.ReadXml(stream, (reader) =>
                {
                    reader.ReadStartElement(typeof(MemoryMaps).Name);

                    while (reader.IsStartElement())
                        m_maps.Add(new MemoryMap(reader));

                    reader.ReadEndElement();
                });
            }
        }

        /// <summary>
        /// Only for development.
        /// </summary>
        public static void SaveToXml()
        {
            XmlWriterExtensions.WriteXml("DefaultMemoryMaps.xml", (writer) =>
            {
                writer.WriteStartElement(typeof(MemoryMaps).Name);

                foreach (var map in m_maps)
                    map.WriteXml(writer);

                writer.WriteEndElement();
            });
        }

        /// <summary>
        /// Only for testing. Return first (if nothing changes 
        /// that's mean simpliest, raw) amiga model memory map.
        /// </summary>
        /// <param name="a_amiga_model"></param>
        /// <returns></returns>
        public static MemoryMap GetMap(AmigaModel a_amiga_model)
        {
            foreach (var def_map in m_maps)
            {
                if (def_map.AmigaModel == a_amiga_model)
                    return def_map;
            }

            return null;
        }

        public static IEnumerable<MemoryMap> Maps
        {
            get
            {
                return m_maps;
            }
        }
    }
}
